<?php
/**
 * image_manager.php
 * Image Manager functions
 * Version 1.8
 *
 * @author  Boudewijn Sjouke <boudewijnsjouke@hotmail.com>
 * @copyright Copyright 2009-2011
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License V2.0
 */

function IMPrintOptionsBlock ($IMimage, $IMstatus, $IMatt, $IMerror, $IMorder, $IMfilter, $prodmsg, $IMcont) {
	
	?>
	<table width=90%>
		<tr class="dataTableHeadingContent dataTableHeadingRow">
			<td colspan=6 align="center">
				<?php print IM_SELECT_OPTIONS;?>
			</td>
		<tr class="dataTableContent dataTableRow" style="vertical-align: top;">
			<td rowspan = "2">
				<?php 
				print "<b>" . IM_SELECT_IMAGE . "</b><br />";
				print zen_draw_radio_field("IMimage", "Ioff", ($IMimage == "Ioff")) . "&nbsp;" . IM_SELECT_IMG_LINK . "<br />";
				print zen_draw_radio_field("IMimage", "Ion", ($IMimage == "Ion")) . "&nbsp;" . IM_SELECT_IMG_IMG . "<br />";
				print zen_draw_radio_field("IMimage", "Iall", ($IMimage == "Iall")) . "&nbsp;" . IM_SELECT_IMG_IMG_ALL . "<br />";
				?>
			</td>
			<td rowspan="2">
				<?php 
				print "<b>" . IM_SELECT_FILE . "</b><br />";
				print zen_draw_radio_field("IMatt", "Fon", ($IMatt == "Fon")) . "&nbsp;" . IM_SELECT_USED . "<br />";
				print zen_draw_radio_field("IMatt", "Foff", ($IMatt == "Foff" || $IMatt == ""), '', "onclick='document.getElementById(\"IMfilter\").value=\"\";'") . "&nbsp;" . IM_SELECT_UNUSED . "<br />";
				?>
			</td>
			<td colspan="4" align="center">
				<?php
				print "<b>" . IM_SELECT_ATTACH_ONLY . "</b>";
				?>
			</td>
		</tr>
		<tr class="dataTableContent dataTableRow" style="vertical-align: top;">
			<td>
				<?php 
				print "<b>" . IM_SELECT_STATUS . "</b><br />";
				print zen_draw_radio_field("IMstatus", "Son", ($IMstatus == "Son"), '', "onclick='document.getElementById(\"IMfilter\").value=\"\";'") . "&nbsp;" . IM_SELECT_ON . "<br />";
				print zen_draw_radio_field("IMstatus", "Soff", ($IMstatus == "Soff"), '', "onclick='document.getElementById(\"IMfilter\").value=\"\";'") . "&nbsp;" . IM_SELECT_OFF . "<br />";
				print zen_draw_radio_field("IMstatus", "Sall", ($IMstatus == "Sall")) . "&nbsp;" . IM_SELECT_ALL . "<br />";
				?>
			</td>
			<td>
				<?php 
				print "<b>" . IM_SELECT_FILE . "</b><br />";
				print zen_draw_radio_field("IMerror", "Eon", ($IMerror == "Eon"), '', "onclick='document.getElementById(\"IMfilter\").value=\"\";'") . "&nbsp;" . IM_SELECT_W_ERR . "<br />";
				print zen_draw_radio_field("IMerror", "Eoff", ($IMerror == "Eoff"), '', "onclick='document.getElementById(\"IMfilter\").value=\"\";'") . "&nbsp;" . IM_SELECT_WO_ERR . "<br />";
				print zen_draw_radio_field("IMerror", "Eall", ($IMerror == "Eall")) . "&nbsp;" . IM_SELECT_ALL . "<br />";
				?>
			</td>
			<td>
				<?php 
				print "<b>" . IM_SELECT_ORDER . "</b><br />";
				print zen_draw_radio_field("IMorder", "Oimage", ($IMorder == "Oimage")) . "&nbsp;" . IM_SELECT_ORDER_FILE . "<br />";
				print zen_draw_radio_field("IMorder", "OID", ($IMorder == "OID")) . "&nbsp;" . IM_SELECT_ORDER_ID . "<br />";
				print zen_draw_radio_field("IMorder", "Olsize", ($IMorder == "Olsize")) . "&nbsp;" . IM_SELECT_ORDER_LARGE_SIZE . "<br />";
				?>
			</td>
			<td>
				<?php
				print "<b>" . IM_SELECT_PID . "</b><br /><br />";
				print IM_ENTER_PID . "&nbsp;" . zen_draw_input_field("IMfilter", $IMfilter, 'size="8" id="IMfilter"');
				print "<br /><br />" . "<span style=\"color:#FF0000;\">" . $prodmsg . "</span>";
				?>
			</td>
		</tr>
		<tr class="dataTableContent dataTableRow">
			<td colspan="6" align="center">
				<?php 
					print zen_image_submit(IM_FILENAME_SEND_BUTTON, IMAGE_SEND);
					if ($IMerror != 'Eoff' && IM_ENABLE_AUTOFIX == 'yes') {
						?><span id="IMautofixstart" style="display:none;">&nbsp;&nbsp;<?php print zen_image_submit(IM_FILENAME_AUTOFIX_BUTTON, IM_AUTOFIX_START, 'id="IMautofixbutton" onclick="IMstartcontinue();return false;"');?></span><?php
						?><span id="IMautofixstop" style="display:none;">&nbsp;&nbsp;<?php print zen_image_submit(IM_FILENAME_AUTOFIX_STOP_BUTTON, IM_AUTOFIX_STOP, 'id="IMautofixstopbutton" value="go" onclick="this.value=\'stop\';return false;"');?></span><?php
					} ?>
			</td>
		</tr>
	</table>
	<?php
}

function IMPrintMessageBlock($IMimage, $IMstatus, $IMatt, $IMerror, $IMorder, $IMpage, $IMorder, $IMfilter, $message="") {
	global $filelist, $image_array, $IMcanupload, $IMerrcheck, $IMcanBAK, $IMmenuonly;
	$count = 0;
	
	?>
	<table width=90%>
		<tr>
			<td style="background-color:#F5F5F5; border: solid #CCCCCC; border-width: 1px 1px;">
			<?php
				print "<b>".IM_MESSAGES . "</b><br />";
				
				// Check for presence of the GD library
				if (!extension_loaded("gd")) {
					IMPrintError(IM_GD_MISSING);
					$IMhasGD = false;
				}
				else $IMhasGD = true;

				// Check for valid configuration values and print errors/links to the config settings
				print IMCheckConfigValues();
								
				// Check all used folders for presence and writability
				$dirread = array();										// Cache for directory status
				$images = array();										// Array of images with all related info
				$resort = false; 										// switch to resort the array after adding additional images
				$IMcanupload = IMCheckUploadFolder();					// Check if we can use the upload folder
				if (!$IMcanBAK) IMCheckBAKfolder(); 					// Force printing of error message
				$IMerrcheck = (!$IMhasGD + !$IMcanupload + !$IMcanBAK); 	// If any errors are found
				
				// Check for presence of watermarks, only for attached files
				if ($IMatt == "Fon") print IMCheckWatermarks() . '.<br />';
				
				// For attached files, me must extend the image_array
				if ($IMatt == "Fon") {
					foreach($filelist as $key => $file) {
						$addfile = IMGetBaseFile($file);
						$basefile = IMGetPrimaryName($addfile);
						if ($addfile != $basefile && isset($image_array[$basefile]) && !isset($image_array[$addfile])) {
							$image_array[$addfile] = $image_array[$basefile];
							// Temporarily indicate it's an additional image
							$image_array[$addfile]['is_additional_image'] = true;
							$resort = true;
						}
							
					}
					if ($resort) {
						if ($IMorder == "Oimage") ksort($image_array);
						else if ($IMorder == "OID") uasort($image_array, "IMIDSort");
					}
				}
				foreach($image_array as $image => $product_array) {
					$p = pathinfo($image);
					if ($p["dirname"] == ".") $p["dirname"] = "";
					else $p["dirname"] .= "/";
					
					if ($IMatt == "Fon") {
						$partlink = "<br /><a href=\"" . zen_href_link(IM_FILENAME, "IMimage=" . $IMimage . "&IMstatus=" . $IMstatus ."&IMatt=" . $IMatt . "&IMerror=" . $IMerror . "&IMorder=" . $IMorder . "&IMfilter=" . $IMfilter . "&IMpage=" . $IMpage);
					
						$images[$image]["filename"] = $image;
						$images[$image]["file"] = $p["filename"];
						$images[$image]["ext"] = $p["extension"];
						$images[$image]["folder"] = $p["dirname"];
					}
					// If we were here before, skip
					if (!array_key_exists(DIR_FS_CATALOG_IMAGES . $p["dirname"], $dirread)) {
						
						// Check if the main folder exists
						if (!is_dir(DIR_FS_CATALOG_IMAGES . $p["dirname"])) {
							// If not, create it
							if (IMCreateDir($p["dirname"], DIR_FS_CATALOG_IMAGES)) {
								print IM_DIR_CREATED . DIR_FS_CATALOG_IMAGES . $p["dirname"] . "<br />";
								$dirread[DIR_FS_CATALOG_IMAGES . $p["dirname"]] = true;
							}
							else {
								$IMerrcheck = true;
								IMPrintError(IM_DIR_EXISTS_ERROR . DIR_FS_CATALOG_IMAGES . $p["dirname"]);
								$dirread[DIR_FS_CATALOG_IMAGES . $p["dirname"]] = false;
							}
						}
						// If it exists, check if we can write in it
						else if (!IMDirIsWritable(DIR_FS_CATALOG_IMAGES . $p["dirname"])) {
							$IMerrcheck = true;
							IMPrintError(IM_DIR_WRITE_ERROR . DIR_FS_CATALOG_IMAGES . $p["dirname"]);
							$dirread[DIR_FS_CATALOG_IMAGES . $p["dirname"]] = false;
						}
						else $dirread[DIR_FS_CATALOG_IMAGES . $p["dirname"]] = true;
						
						// Check if the medium folder exists, if not disabled
						if (IM_USE_MEDIUM_IMAGES == "enable") {
							if (!is_dir(DIR_FS_CATALOG_IMAGES. "medium/" . $p["dirname"])) {
								// If not, create it
								if (IMCreateDir($p["dirname"], DIR_FS_CATALOG_IMAGES . "medium/")) {
									print IM_DIR_CREATED . DIR_FS_CATALOG_IMAGES . "medium/"  . $p["dirname"] . "<br />";
									$dirread[DIR_FS_CATALOG_IMAGES . "medium/" . $p["dirname"]] = true;
								}
								else {
									$IMerrcheck = true;
									IMPrintError(IM_DIR_EXISTS_ERROR . DIR_FS_CATALOG_IMAGES . "medium/" . $p["dirname"]);
									$dirread[DIR_FS_CATALOG_IMAGES . "medium/" . $p["dirname"]] = false;
								}
							}
							// If it exists, check if we can write in it
							else if (!IMDirIsWritable(DIR_FS_CATALOG_IMAGES. "medium/" . $p["dirname"])) {
								$IMerrcheck = true;
								IMPrintError(IM_DIR_WRITE_ERROR . DIR_FS_CATALOG_IMAGES. "medium/" . $p["dirname"]);
								$dirread[DIR_FS_CATALOG_IMAGES . "medium/" . $p["dirname"]] = false;
							}
							else $dirread[DIR_FS_CATALOG_IMAGES . "medium/" . $p["dirname"]] = true;
						}

						// Check if the large folder exists
						if (!is_dir(DIR_FS_CATALOG_IMAGES . "large/" . $p["dirname"])) {
							// If not, create it
							if (IMCreateDir($p["dirname"], DIR_FS_CATALOG_IMAGES . "large/")) {
								print IM_DIR_CREATED . DIR_FS_CATALOG_IMAGES . "large/"  . $p["dirname"] . '<br />';
								$dirread[DIR_FS_CATALOG_IMAGES . "large/" . $p["dirname"]] = true;
							}
							else {
								$IMerrcheck = true;
								IMPrintError(IM_DIR_EXISTS_ERROR . DIR_FS_CATALOG_IMAGES . "large/" . $p["dirname"]);
								$dirread[DIR_FS_CATALOG_IMAGES . "large/" . $p["dirname"]] = false;
							}
						}
						// If it exists, check if we can write in it
						else if (!IMDirIsWritable(DIR_FS_CATALOG_IMAGES . "large/" . $p["dirname"])) {
							$IMerrcheck = true;
							IMPrintError(IM_DIR_WRITE_ERROR . DIR_FS_CATALOG_IMAGES. "large/" . $p["dirname"]);
							$dirread[DIR_FS_CATALOG_IMAGES . "large/" . $p["dirname"]] = false;
						}
						else $dirread[DIR_FS_CATALOG_IMAGES . "large/" . $p["dirname"]] = true;

					}

					if ($IMatt == "Fon") {
						// Collect information about the images
						
						// Here code to check for additional images. If found, add them to the array to process.
						
						// General status for this image
						$status_ok = true;
						
						// Small file
						$filename_small = DIR_FS_CATALOG_IMAGES . $p["dirname"] . $p["filename"] . "." . $p["extension"]; 
						
						// Check for existence
						if (file_exists($filename_small)) {
							$images[$image]["small"]["exists"] = true;
							// Check if it's an image
							if ($imgsize = @getimagesize($filename_small)) {
								$images[$image]["small"]["is_image"] = true;
								$images[$image]["small"]["width"] = $imgsize[0];
								$images[$image]["small"]["height"] = $imgsize[1];
								$images[$image]["small"]["size"] = filesize($filename_small)/1024;
								
								// Check if it's bigger than will be displayed 
								$cw = $imgsize[0] / SMALL_IMAGE_WIDTH;
								$ch = $imgsize[1] / SMALL_IMAGE_HEIGHT;
								if ($cw > 1 || $ch > 1) {
									$images[$image]["small"]["too_big"] = true;
									$status_ok = false;
								}
								else $images[$image]["small"]["too_big"] = false;
								
								// Prepare the link to show the image
								$file = HTTP_CATALOG_SERVER . DIR_WS_CATALOG . DIR_WS_IMAGES . $p["dirname"] . $p["filename"] . "." . $p["extension"];
								if ($IMimage == "Ion" || $IMimage == "Iall" || ($IMimage == "Ioff" && IM_SHOW_POPUP_IMAGE == "image")) {
									if ($cw > $ch) {
										$wh = "width=\"".SMALL_IMAGE_WIDTH."\"";
									}
									else {
										$wh = "height=\"".SMALL_IMAGE_HEIGHT."\"";
									}
									if ($IMimage == "Ion" || $IMimage == "Iall") {
										$images[$image]["small"]["url"] = "<img src=\"".$file."?rand=".time()."\" alt=\"".$file."\" ".$wh." />";
										$savewh = $wh;
									}
								}
								else $images[$image]["small"]["url"] = "<a href=\"#\" onclick=\"IMpopwin('" . $file . "', 'IMpopup', " . $imgsize[0] . ", " . $imgsize[1] . "); return false;\">" . IM_SELECT_IMG_LINK_CLICK ."</a>";
								if ($IMimage == "Ioff" && IM_SHOW_POPUP_IMAGE == "image") $images[$image]["popuplink"] = "<img src=\"".$file."?rand=".time()."\" alt=\"".$file."\" ".$wh." />";
									
							}
							else {
								$images[$image]["small"]["is_image"] = false;
								$status_ok = false;
							}
						}
						else {
							$images[$image]["small"]["exists"] = false;
							$status_ok = false;
						}
		
						// Medium file, if not set to disabled
						if (IM_USE_MEDIUM_IMAGES == "enable") {
							$filename_medium = DIR_FS_CATALOG_IMAGES . 'medium/' . $p["dirname"] . $p["filename"] . IMAGE_SUFFIX_MEDIUM . "." . $p["extension"];
							
							// Check for existence
							if (file_exists($filename_medium)) {
								$images[$image]["medium"]["exists"] = true;
								// Check if it's an image
								if ($imgsize = @getimagesize($filename_medium)) {
									$images[$image]["medium"]["is_image"] = true;
									$images[$image]["medium"]["width"] = $imgsize[0];
									$images[$image]["medium"]["height"] = $imgsize[1];
									$images[$image]["medium"]["size"] = filesize($filename_medium)/1024;
									
									// Check if it's bigger than will be displayed 
									$cw = $imgsize[0] / MEDIUM_IMAGE_WIDTH;
									$ch = $imgsize[1] / MEDIUM_IMAGE_HEIGHT;
									if ($cw > 1 || $ch > 1) {
										$images[$image]["medium"]["too_big"] = true;
										$status_ok = false;
									}
									else {
										$images[$image]["medium"]["too_big"] = false;
										$images[$image]["medium"]["delete_link"] = ($dirread[DIR_FS_CATALOG_IMAGES . "medium/" . $p["dirname"]] == true && IMFileIsWriteable($filename_medium) ? $partlink. "&actcnt=" . ($_SESSION["actcnt"] + 1) . "&IMaction=deletefile&filename=" . urlencode('medium/' . $p["dirname"] . $p["filename"] . IMAGE_SUFFIX_MEDIUM . "." . $p["extension"]) . "\" onclick=\"return confirm('" . IM_CONFIRM_SINGLE_DELETE . "');\" />". IM_IMAGE_DELETE . "</a>" : ""); 
									}
									if ($IMimage == "Iall") {
										$file = HTTP_CATALOG_SERVER . DIR_WS_CATALOG . DIR_WS_IMAGES . 'medium/'. $p["dirname"] . $p["filename"] . "_MED." . $p["extension"];
										if ($cw > $ch) $wh = "width=\"".SMALL_IMAGE_WIDTH."\"";
										else $wh = "height=\"".SMALL_IMAGE_HEIGHT."\"";
										$images[$image]["medium"]["url"] = "<img src=\"".$file."?rand=".time()."\" alt=\"".$file."\" ".$wh." />";
									}
									
								}
								else {
									$images[$image]["medium"]["is_image"] = false;
									$status_ok = false;
								}
							}
							else {
								$images[$image]["medium"]["exists"] = false;
								$status_ok = false;
							}
						}
						
						// Large file
						$filename_large = DIR_FS_CATALOG_IMAGES . 'large/' . $p["dirname"] . $p["filename"] . IMAGE_SUFFIX_LARGE . "." . $p["extension"];
						
						// Check for existence
						if (file_exists($filename_large)) {
							$images[$image]["large"]["exists"] = true;
							// Check if it's an image
							if ($imgsize = @getimagesize($filename_large)) {
								$images[$image]["large"]["is_image"] = true;
								$images[$image]["large"]["width"] = $imgsize[0];
								$images[$image]["large"]["height"] = $imgsize[1];
								$images[$image]["large"]["size"] = filesize($filename_large)/1024;
								
								// Check if the size is smaller than medium. If so, it might be too SMALL for a large image!
								// Width and height must be bigger than a medium image
								$cw = $imgsize[0] / MEDIUM_IMAGE_WIDTH;
								$ch = $imgsize[1] / MEDIUM_IMAGE_HEIGHT;
								if ($cw <= 1 || $ch <= 1) {
									$images[$image]["large"]["too_small"] = true;
									$status_ok = false;
								}
								else {
									$images[$image]["large"]["too_small"] = false;
									$images[$image]["large"]["delete_link"] = ($dirread[DIR_FS_CATALOG_IMAGES . "large/" . $p["dirname"]] == true && IMFileIsWriteable($filename_large) ? $partlink. "&actcnt=" . ($_SESSION["actcnt"] + 1) . "&IMaction=deletefile&filename=" . urlencode('large/' . $p["dirname"] . $p["filename"] . IMAGE_SUFFIX_LARGE . "." . $p["extension"]) . "\"  onclick=\"return confirm('" . IM_CONFIRM_SINGLE_DELETE . "');\" />". IM_IMAGE_DELETE . "</a>" : ""); 
								}
								// Check if the size is bigger than the setting for large.
								$cw = $imgsize[0] / IM_MAX_LARGE_WIDTH;
								$ch = $imgsize[1] / IM_MAX_LARGE_HEIGHT;
								if ($cw > 1 || $ch > 1) {
									$images[$image]["large"]["too_big"] = true;
									$status_ok = false;
								}
								else {
									$images[$image]["large"]["too_big"] = false;
								}
								if ($IMimage == "Iall") {
									$file = HTTP_CATALOG_SERVER . DIR_WS_CATALOG . DIR_WS_IMAGES . 'large/'. $p["dirname"] . $p["filename"] . "_LRG." . $p["extension"];
									if ($cw > $ch) $wh = "width=\"".SMALL_IMAGE_WIDTH."\"";
									else $wh = "height=\"".SMALL_IMAGE_HEIGHT."\"";
									$images[$image]["large"]["url"] = "<img src=\"".$file."?rand=".time()."\" alt=\"".$file."\" ".$wh." />";
								}
							}
							else {
								$images[$image]["large"]["is_image"] = false;
								$status_ok = false;
							}
						}
						else {
							$images[$image]["large"]["exists"] = false;
							$status_ok = false;
						}
						
						// Set the final status of the image
						$images[$image]["status_ok"] = $status_ok;
						
						// Move the indication for additional image
						if (isset($product_array['is_additional_image'])) $images[$image]["is_additional_image"] = true;
						if ($IMerror == "Eall" || ($IMerror == "Eon" && !$images[$image]["status_ok"]) || ($IMerror == "Eoff" && $images[$image]["status_ok"])) {
							$images[$image]["action"] = IMCheckAction($images[$image], $IMimage, $IMstatus, $IMatt, $IMerror, $IMorder, $IMfilter, $IMpage);
						}
					}
					else {
						// Add the small name to the array
						$images[] = DIR_FS_CATALOG_IMAGES . $p["dirname"] . $p["filename"] . "." . $p["extension"];
						// Add the middle images to the array, if not excluded
						if (IM_USE_MEDIUM_IMAGES == "enable") $images[] = DIR_FS_CATALOG_IMAGES . 'medium/' . $p["dirname"] . $p["filename"] . IMAGE_SUFFIX_MEDIUM . "." . $p["extension"];
						$images[] = DIR_FS_CATALOG_IMAGES . 'large/' . $p["dirname"] . $p["filename"] . IMAGE_SUFFIX_LARGE . "." . $p["extension"];
					}
					if (isset($product_array['is_additional_image'])) unset($image_array[$image]['is_additional_image']);
				}
				
				// for unattached files, process further
				if ($IMatt == "Foff") {
					// diff the actual filelist to the filelist derived from the DB. What remains is files that are not primary files (small, medium, large)
					// to make a true diff 
					$filesU = array_diff($filelist, $images);
					// Normalise the remaining files and check for additional ones.
					foreach ($filesU as $key => $loosefile) {
						$loosefile = IMGetPrimaryName(IMGetBaseFile($loosefile));
						// After removal, we should have the primary filename, which we check in the filelist from the DB
						if (isset($image_array[$loosefile])) {
							unset($filesU[$key]);
						}
					}
					// If on WIN, we need to check for differences in upper/lowercase names in DB and files
					if (IM_IS_WIN) {
						$imagessave = $images;
						array_walk($imagessave, "IMToLower");
					}
					// Here we have the really unattached files. Now we check if folder and file are writable.
					// We use the previously created $dirread, but have to check further, as not all folders may be checked yet
					$images = array();
					foreach ($filesU as $key => $file) {
						$p = pathinfo($file);
						if ($p["dirname"] == ".") $p["dirname"] = "";
						else $p["dirname"] .= "/";
						if (!array_key_exists($p["dirname"], $dirread)) {
							if (!IMDirIsWritable($p["dirname"])) {
								print IM_DIR_WRITE_ERROR . $p["dirname"] . "<br />";
								$IMerrcheck = true;
								$dirread[$p["dirname"]] = false;
							}
							else $dirread[$p["dirname"]] = true;
						}
						if ($dirread[$p["dirname"]] && IMFileIsWriteable($file)) $images[$file]["canwrite"] = true;
						else $images[$file]["canwrite"] = false;
						if (IM_IS_WIN) {
							if(in_array(strtolower($file), $imagessave)) $images[$file]["mismatch"] = true;
							else $images[$file]["mismatch"] = false;
						}
					}
				}
				if(!$IMerrcheck && !$IMmenuonly) print IM_NO_CHECK_ERRORS;
				if (!empty($message)) IMPrintError($message, false);
			?>
			</td>
		</tr>
	</table>
	<?php
	return $images;
}
function IMToLower(&$string) {
	
	$string = strtolower($string);
}

function IMGetBaseFile($filename) {

	// bring medium/large back to small, and strip the images folder part of the file (not included in DB file names)
	return str_replace(array(DIR_FS_CATALOG_IMAGES, 'medium/', 'large/', IMAGE_SUFFIX_MEDIUM . '.', IMAGE_SUFFIX_LARGE . '.'), array('', '', '', '.', '.'), $filename);
}

function IMGetPrimaryName($filename) {
	
	// Check for underscore suffixes at the end of the name part of the file and remove them
	return preg_replace("/_[^_]+\./", ".", $filename);
}

function IMCheckAction($image, $IMimage, $IMstatus, $IMatt, $IMerror, $IMorder, $IMfilter, $IMpage) {
	global $IMcanupload;
	global $IMwmsmall, $IMwmmedium, $IMwmlarge;
	global $IMcombinedactions;

	// Combined actions:
	if (!isset($IMcombinedactions)) $IMcombinedactions = array();
	$cnew = true;
	// combinednew    : copy small to medium (if used) and large; resize small.
	//                  action can be performed if medium (if used) and large don't exist, 
	//                  and small is big enough to copy to medium (if used) and large.
	$creplace = true;
	// combinedreplace: delete medium (if used) and large; copy small to medium (if used) and large; resize small.
	//                  action can be performed if medium (if used) and large exist, and small is big enough to copy to medium (if used) and large.
	
	// Initialise the actions
	$action = array();
	$action["small"] = array();
	$action["medium"] = array();
	$action["large"] = array();
	
	$url = zen_href_link(IM_FILENAME, "IMimage=" . $IMimage . "&IMstatus=" . $IMstatus ."&IMatt=" . $IMatt . "&IMerror=" . $IMerror . "&IMorder=" . $IMorder . "&IMfilter=" . $IMfilter . "&IMpage=" . $IMpage);
	$partlink = "<a href=\"" . $url;
	 
	// 0. No action required, then skip the rest, except the reupload link
	if (!$image["status_ok"]) {
		
		// 1. There is a file in small, but not in medium. Only do this if medium images are enabled
		if (IM_USE_MEDIUM_IMAGES == "enable") {
			if ($image["small"]["exists"] && !$image["medium"]["exists"]) {
				// Check if the small image is large enough for copy/resize to medium
				if ($image["small"]["width"] >= MEDIUM_IMAGE_WIDTH || $image["small"]["height"] >= MEDIUM_IMAGE_HEIGHT) {
					if (IMDirIsWritable(DIR_FS_CATALOG_IMAGES . "medium/" . $image["folder"])) $action["medium"][] = $partlink . "&IMaction=createimagemedfromsmall&image=" . urlencode($image["filename"]) . "\">" . IM_CREATE_FROM_SMALL . "</a>";
				}
				// if not, we cannot do the combined actions
				else $cnew = false;
			}
		}
		// 2. There is a file in small, but not in large
		if ($image["small"]["exists"] && !$image["large"]["exists"]) {
			// Check if the small image is large enough for copy/resize to large
			if ($image["small"]["width"] > MEDIUM_IMAGE_WIDTH && $image["small"]["height"] > MEDIUM_IMAGE_HEIGHT) {
				if (IMDirIsWritable(DIR_FS_CATALOG_IMAGES . "large/" . $image["folder"])) $action["large"][] = $partlink . "&IMaction=createimagelargefromsmall&image=" . urlencode($image["filename"]) . "\">" . IM_CREATE_FROM_SMALL . "</a>";
			}
			// if not, we cannot do the combined actions
			else $cnew = false;
		}
		// 3. There is a file in small, medium and large and small is too big
		if ($image["small"]["exists"] && (IM_USE_MEDIUM_IMAGES == "disable" || $image["medium"]["exists"]) && $image["large"]["exists"]) {
			// Check if the small image is large enough for copy/resize to large
			if (($image["small"]["width"] > SMALL_IMAGE_WIDTH || $image["small"]["height"] > SMALL_IMAGE_HEIGHT) && IMDirIsWritable(DIR_FS_CATALOG_IMAGES . $image["folder"]) && IMFileIsWriteable(DIR_FS_CATALOG_IMAGES . $image["filename"])) {
				$action["small"][] = $partlink . "&IMaction=resizesmall&image=" . urlencode($image["filename"]) . "\">" . IM_CREATE_SMALLER . "</a>";
			}
		}
		// 3. There is a file in small, medium and large and medium is too big. Only do this if medium is enabled
		if (IM_USE_MEDIUM_IMAGES == "enable") {
			if ($image["small"]["exists"] && $image["medium"]["exists"] && $image["large"]["exists"]) {
				// Check if the small image is large enough for copy/resize to large
				if (($image["medium"]["width"] > MEDIUM_IMAGE_WIDTH || $image["medium"]["height"] > MEDIUM_IMAGE_HEIGHT)  && IMDirIsWritable(DIR_FS_CATALOG_IMAGES . "medium/" . $image["folder"]) && IMFileIsWriteable(DIR_FS_CATALOG_IMAGES . "medium/" . $image["folder"] . $image["file"] . IMAGE_SUFFIX_MEDIUM . ".". $image["ext"])) {
					$action["medium"][] = $partlink . "&IMaction=resizemedium&image=" . urlencode("medium/" . $image["folder"] . $image["file"] . IMAGE_SUFFIX_MEDIUM . ".". $image["ext"]) . "\">" . IM_CREATE_SMALLER . "</a>";
				}
			}
		}
		// 4. There is a file in small, medium and large and large is too big
		if ($image["small"]["exists"] && (IM_USE_MEDIUM_IMAGES == "disable" || $image["medium"]["exists"]) && $image["large"]["exists"]) {
			// Check if the small image is large enough for copy/resize to large
			if (($image["large"]["width"] > IM_MAX_LARGE_WIDTH || $image["large"]["height"] > IM_MAX_LARGE_HEIGHT) && IMDirIsWritable(DIR_FS_CATALOG_IMAGES . "large/" . $image["folder"]) && IMFileIsWriteable(DIR_FS_CATALOG_IMAGES . "large/" . $image["folder"] . $image["file"] . IMAGE_SUFFIX_LARGE . ".". $image["ext"])) {
				$action["large"][] = $partlink . "&IMaction=resizelarge&image=" . urlencode("large/" . $image["folder"] . $image["file"] . IMAGE_SUFFIX_LARGE . ".". $image["ext"]) . "\">" . IM_CREATE_SMALLER . "</a>";
			}
		}
		// 4a. If it's additional image, small exists and medium/large don't exist, we must be able to delete small
		if (isset($image["is_additional_image"]) && $image["is_additional_image"] == true && $image["small"]["exists"] && (IM_USE_MEDIUM_IMAGES == "disable" || !$image["medium"]["exists"]) && !$image["large"]["exists"]) {
			if (IMDirIsWritable(DIR_FS_CATALOG_IMAGES . $image["folder"]) && IMFileIsWriteable(DIR_FS_CATALOG_IMAGES . $image["folder"] . $image["file"] . ".". $image["ext"])) {
				$action["small"][] = $partlink. "&actcnt=" . ($_SESSION["actcnt"] + 1) . "&IMaction=deletefile&filename=" . urlencode($image["folder"] . $image["file"] . "." . $image["ext"]) . "\" onclick=\"return confirm('" . IM_CONFIRM_SINGLE_DELETE . "');\" />". IM_IMAGE_DELETE . "</a>"; 
			}
		}
		// 7. if we can perform the combinednew action, we display the link
		if ($cnew && $image["small"]["exists"] && (IM_USE_MEDIUM_IMAGES == "disable" || !$image["medium"]["exists"]) && !$image["large"]["exists"]) {
			if (IMDirIsWritable(DIR_FS_CATALOG_IMAGES . "medium/" . $image["folder"]) && IMDirIsWritable(DIR_FS_CATALOG_IMAGES . "large/" . $image["folder"])) {
				 $action["small"][] = $partlink . "&IMaction=combinednew&image=" . urlencode($image["folder"] . $image["file"] . ".". $image["ext"]) . "\">" . IM_COMBINED_NEW . "</a>";
				 if ($IMerror != 'Eoff' && IM_ENABLE_AUTOFIX) $IMcombinedactions[] = array('url' => $url . "&IMcont=1&IMaction=combinednew&image=" . urlencode($image["folder"] . $image["file"] . ".". $image["ext"]), 'image' => $image['filename']);
			 }
		}
		
		// 7. if we can perform the combinedreplace action, we display the link
		if ($cnew && $image["small"]["exists"] && (IM_USE_MEDIUM_IMAGES == "disable" || $image["medium"]["exists"]) && $image["large"]["exists"]) {
			if (IMDirIsWritable(DIR_FS_CATALOG_IMAGES . "medium/" . $image["folder"]) && IMDirIsWritable(DIR_FS_CATALOG_IMAGES . "large/" . $image["folder"]) && (IM_USE_MEDIUM_IMAGES == "disable" || IMFileIsWriteable(DIR_FS_CATALOG_IMAGES . "medium/" . $image["folder"] . $image["file"] . IMAGE_SUFFIX_MEDIUM . ".". $image["ext"])) && IMFileIsWriteable(DIR_FS_CATALOG_IMAGES . "large/" . $image["folder"] . $image["file"] . IMAGE_SUFFIX_LARGE . ".". $image["ext"])) {
				$action["small"][] = $partlink . "&IMaction=combinedreplace&image=" . urlencode($image["folder"] . $image["file"] . ".". $image["ext"]) . "\">" . IM_COMBINED_REPLACE . "</a>";
				 if ($IMerror != 'Eoff' && IM_ENABLE_AUTOFIX) $IMcombinedactions[] = array('url' => $url . "&IMcont=1&IMaction=combinedreplace&image=" . urlencode($image["folder"] . $image["file"] . ".". $image["ext"]), 'image' => $image['filename']);
			}
		}
	}
	else {
		// if it's an additional image, we can set the action to delete all two/three
		if (isset($image["is_additional_image"]) && $image["is_additional_image"] == true) {
			if (IMDirIsWritable(DIR_FS_CATALOG_IMAGES . "medium/" . $image["folder"]) && IMDirIsWritable(DIR_FS_CATALOG_IMAGES . "large/" . $image["folder"]) && (IM_USE_MEDIUM_IMAGES == "disable" || IMFileIsWriteable(DIR_FS_CATALOG_IMAGES . "medium/" . $image["folder"] . $image["file"] . IMAGE_SUFFIX_MEDIUM . ".". $image["ext"])) && IMFileIsWriteable(DIR_FS_CATALOG_IMAGES . "large/" . $image["folder"] . $image["file"] . IMAGE_SUFFIX_LARGE . ".". $image["ext"]) && IMDirIsWritable(DIR_FS_CATALOG_IMAGES . $image["folder"]) && IMFileIsWriteable(DIR_FS_CATALOG_IMAGES . $image["filename"])) {
				$action["small"][] = $partlink . "&IMaction=deletesizes&image=" . urlencode($image["folder"] . $image["file"] . ".". $image["ext"]) . "\">" . IM_DEL_ADDITIONAL_IMAGE . "</a>";;
			}
		}
		// The image is ok, so we cannot perform combinednew
		if (IM_SHOW_WATERMARK_LINK == 'yes') {
			// 5. Add the watermark options, but only if all images are ok
			if ($IMwmsmall && count($action["small"]) == 0 && IMDirIsWritable(DIR_FS_CATALOG_IMAGES . $image["folder"]) && IMFileIsWriteable(DIR_FS_CATALOG_IMAGES . $image["folder"] . $image["file"] . ".". $image["ext"])) {
				$action["large"][] = $partlink . "&actcnt=" . ($_SESSION["actcnt"] + 1) . "&IMaction=addwatermark&size=small&image=" . urlencode($image["filename"]) . "\">" . IM_ADD_WATERMARK . "</a>";
			}
			if ($IMwmmedium && count($action["medium"]) == 0 && IMDirIsWritable(DIR_FS_CATALOG_IMAGES . "medium/" . $image["folder"]) && IMFileIsWriteable(DIR_FS_CATALOG_IMAGES . "medium/" . $image["folder"] . $image["file"] . IMAGE_SUFFIX_MEDIUM . ".". $image["ext"])) {
				$action["medium"][] = $partlink . "&actcnt=" . ($_SESSION["actcnt"] + 1) . "&IMaction=addwatermark&size=medium&image=" . urlencode("medium/" . $image["folder"] . $image["file"] . IMAGE_SUFFIX_MEDIUM . ".". $image["ext"]) . "\">" . IM_ADD_WATERMARK . "</a>";
			}
			if ($IMwmlarge && count($action["large"]) == 0 && IMDirIsWritable(DIR_FS_CATALOG_IMAGES . "large/" . $image["folder"]) && IMFileIsWriteable(DIR_FS_CATALOG_IMAGES . "large/" . $image["folder"] . $image["file"] . IMAGE_SUFFIX_LARGE . ".". $image["ext"])) {
				$action["large"][] = $partlink . "&actcnt=" . ($_SESSION["actcnt"] + 1) . "&IMaction=addwatermark&size=large&image=" . urlencode("large/" . $image["folder"] . $image["file"] . IMAGE_SUFFIX_LARGE . ".". $image["ext"]) . "\">" . IM_ADD_WATERMARK . "</a>";
			}
		}
	}	
	// 6. If the upload folder is writable, we must be able to re-upload the image from the local computer
	if (IM_SHOW_REUPLOAD_LINK == 'yes' && $IMcanupload == true && IMDirIsWritable(DIR_FS_CATALOG_IMAGES . $image["folder"]) && (!file_exists(DIR_FS_CATALOG_IMAGES . $image["filename"]) || IMFileIsWriteable(DIR_FS_CATALOG_IMAGES . $image["filename"]))) $action["small"][] = "<a href=\"javascript:" . IM_REUPLOAD_IMAGE . "\" onclick='popupWindow(\"" . zen_href_link(IM_UPLOAD_POPUP, 'imname=' . urlencode($image["filename"])) . "\"); return false;'>"  . IM_REUPLOAD_IMAGE . '</a>';
	
	
	return $action;			
}

function IMCheckWatermarks() {
	global $IMwmsmall, $IMwmmedium, $IMwmlarge;
	
	if (!isset($IMwmsmall)) $IMwmsmall = file_exists(DIR_FS_CATALOG_IMAGES . "watermark.png");
	if (!isset($IMwmmedium)) $IMwmmedium = file_exists(DIR_FS_CATALOG_IMAGES . 'medium/' . "watermark.png");
	if (!isset($IMwmlarge)) $IMwmlarge = file_exists(DIR_FS_CATALOG_IMAGES . 'large/' . "watermark.png");

	if ($IMwmsmall || $IMwmmedium || $IMwmlarge) {
		$txt = array();
		if ($IMwmsmall) $txt[] = IM_SMALL;
		if ($IMwmmedium) $txt[] = IM_MEDIUM;
		if ($IMwmlarge) $txt[] = IM_LARGE;
		return IM_WATERMARKS_PRESENT . ' ' . implode(', ', $txt);
	}
	else return IM_NO_WATERMARKS_PRESENT;
}

function IMCheckConfigValues() {

	$return_message = "";
	$config_values = array(
		"SMALL_IMAGE_WIDTH" => array(1, (IM_USE_MEDIUM_IMAGES == "enable" ? MEDIUM_IMAGE_WIDTH : IM_MAX_LARGE_WIDTH)),
		"SMALL_IMAGE_HEIGHT" => array(1, (IM_USE_MEDIUM_IMAGES == "enable" ? MEDIUM_IMAGE_HEIGHT : IM_MAX_LARGE_HEIGHT)),
		"IM_MAX_LARGE_WIDTH" => array((IM_USE_MEDIUM_IMAGES == "enable" ? MEDIUM_IMAGE_WIDTH : SMALL_IMAGE_WIDTH), 999999),
		"IM_MAX_LARGE_HEIGHT" => array((IM_USE_MEDIUM_IMAGES == "enable" ? MEDIUM_IMAGE_HEIGHT : SMALL_IMAGE_HEIGHT), 999999),
		"IM_WM_HSIZE" => array(1, 100),
		"IM_WM_HMARGIN" => array(0, 100),
		"IM_WM_VMARGIN"	=> array(0, 100),
		"IM_PAGE_LENGTH" => array(1, 999999)
	);
	if (IM_USE_MEDIUM_IMAGES == "enable") {
		$config_values["MEDIUM_IMAGE_WIDTH"] = array(SMALL_IMAGE_WIDTH, IM_MAX_LARGE_WIDTH);
		$config_values["MEDIUM_IMAGE_HEIGHT"] = array(SMALL_IMAGE_HEIGHT, IM_MAX_LARGE_HEIGHT);
	}
	foreach($config_values as $constant => $value_array) {
		if (!is_numeric(constant($constant))) {
			$return_message .= IM_ERROR_NUMERIC . ' ' .  '<a href="' . zen_href_link(FILENAME_CONFIGURATION, IMGetConfigGroup($constant) . '&amp;action=edit">') . constant('IM_TEXT_' . $constant) . '</a><br />';
		}
		else {
			if (constant($constant) < $value_array[0] || constant($constant) > $value_array[1]) {
			$return_message .= IM_ERROR_VALUE . ' ' .  '<a href="' . zen_href_link(FILENAME_CONFIGURATION, IMGetConfigGroup($constant) . '&amp;action=edit">') . constant('IM_TEXT_' . $constant) . '</a><br />';
			}
		}
	}
	return $return_message;
}

function IMGetConfigGroup($key) {
	global $db;
	
	$key = zen_db_prepare_input($key);
	$ckey = $db->Execute('SELECT configuration_id, configuration_group_id FROM ' . TABLE_CONFIGURATION . ' WHERE configuration_key = "' . $key . '"');
	$return_value = '';
	while (!$ckey->EOF) {
		$return_value = 'gID=' . $ckey->fields['configuration_group_id'] . '&amp;cID=' . $ckey->fields['configuration_id'];
		$ckey->MoveNext();
	}
	return $return_value;
}
	

function IMPerformAction($action, $image) {
	
	// print "action: ".$action."<br />";
	// print "image: ".$image."<br />";
	// Parse the file characteristics
	$p = pathinfo($image);
	if ($p["dirname"] == ".") $p["dirname"] = "";

	// Create a separate watermark

	if ($action == "addwatermark" && $_GET["actcnt"] != $_SESSION["actcnt"]) {
		$source = DIR_FS_CATALOG_IMAGES . $image;
		if (isset($_GET['size'])) $size = $_GET['size'];
		else $size = "small";
		$target_root = DIR_FS_CATALOG_IMAGES . ($size == 'small' ? '' : ($size == 'medium/' ? 'medium' : 'large/'));
		$target = $source;
		$_SESSION["actcnt"] = $_GET["actcnt"];
		return IMAddWaterMark($source, $target, $target_root, $size);
	}
		
	// Create large image from small image
	if ($action == "createimagelargefromsmall") {
		// print "create large from small<br />";
		$source = DIR_FS_CATALOG_IMAGES . $p["dirname"] . "/" . $p["filename"] . "." . $p["extension"];
		$target_root = DIR_FS_CATALOG_IMAGES . 'large/';
		$target = $target_root . $p["dirname"] . "/" . $p["filename"] . IMAGE_SUFFIX_LARGE . "." . $p["extension"];
		return IMAddWaterMark($source, $target, $target_root, "large");
	}
	// Create medium image from small image
	else if ($action == "createimagemedfromsmall") {
		$source = DIR_FS_CATALOG_IMAGES . $p["dirname"] . "/" . $p["filename"] . "." . $p["extension"];
		$target_root = DIR_FS_CATALOG_IMAGES . 'medium/';
		$target = $target_root . $p["dirname"] . "/" . $p["filename"] . IMAGE_SUFFIX_MEDIUM . "." . $p["extension"];
		return IMAddWaterMark($source, $target, $target_root, "medium");
	}
	// Resize small image
	else if ($action == "resizesmall" || $action == "resizemedium") {
		$source = DIR_FS_CATALOG_IMAGES . $p["dirname"] . "/" . $p["filename"] . "." . $p["extension"];
		$target_root = DIR_FS_CATALOG_IMAGES;
		$target = $target_root . $p["dirname"] . "/" . $p["filename"] . "." . $p["extension"];
		// print $source."<br />".$target;
		if ($action == "resizesmall") return IMAddWaterMark($source, $target, $target_root, "small");
		if ($action == "resizemedium") return IMAddWaterMark($source, $target, $target_root, "medium");
	}
	// Resize large image
	else if ($action == "resizelarge") {
		$target_root = DIR_FS_CATALOG_IMAGES;
		$source = $target_root . $p["dirname"] . "/" . $p["filename"] . "." . $p["extension"];
		$target = $target_root . $p["dirname"] . "/" . $p["filename"] . "." . $p["extension"];
		// print $source."<br />".$target;
		return IMAddWaterMark($source, $target, $target_root, "large", false);
	}
	// Combined action combinednew
	else if ($action == 'combinednew') {
		if (IM_USE_MEDIUM_IMAGES) $message = IMPerformAction('createimagemedfromsmall', $image);
		else $message = '';
		if (empty($message)) $message = IMPerformAction('createimagelargefromsmall', $image);
		if (empty($message)) $message = IMPerformAction('resizesmall', $image);
		return $message;
	}
	// Combined action combinednew
	else if ($action == 'combinedreplace') {
		if (IM_USE_MEDIUM_IMAGES) $message = (@unlink(DIR_FS_CATALOG_IMAGES . 'medium/' . $p['dirname'] . '/' . $p["filename"] . IMAGE_SUFFIX_MEDIUM . "." . $p["extension"]) ? '' : '<br />' . IM_CANNOT_DELETE . ' ' . DIR_FS_CATALOG_IMAGES . 'medium/' . $p['dirname'] . '/' . $p["filename"] . IMAGE_SUFFIX_MEDIUM . "." . $p["extension"]);
		else $message = '';
		$message .= (@unlink(DIR_FS_CATALOG_IMAGES . 'large/' . $p['dirname'] . '/' . $p["filename"] . IMAGE_SUFFIX_LARGE . "." . $p["extension"]) ? '' : '<br />' . IM_CANNOT_DELETE . ' ' . DIR_FS_CATALOG_IMAGES . 'large/' . $p['dirname'] . '/' . $p["filename"] . IMAGE_SUFFIX_LARGE . "." . $p["extension"]);
		if (empty($message)) $message = IMPerformAction('combinednew', $image);
		return $message;
	}
	// Delete all 2 or 3 image sizs
	else if ($action == 'deletesizes') {
		if (IM_USE_MEDIUM_IMAGES) $message = (@unlink(DIR_FS_CATALOG_IMAGES . 'medium/' . $p['dirname'] . '/' . $p["filename"] . IMAGE_SUFFIX_MEDIUM . "." . $p["extension"]) ? '' : '<br />' . IM_CANNOT_DELETE . ' ' . DIR_FS_CATALOG_IMAGES . 'medium/' . $p['dirname'] . '/' . $p["filename"] . IMAGE_SUFFIX_MEDIUM . "." . $p["extension"]);
		else $message = '';
		$message .= (@unlink(DIR_FS_CATALOG_IMAGES . 'large/' . $p['dirname'] . '/' . $p["filename"] . IMAGE_SUFFIX_LARGE . "." . $p["extension"]) ? '' : '<br />' . IM_CANNOT_DELETE . ' ' . DIR_FS_CATALOG_IMAGES . 'large/' . $p['dirname'] . '/' . $p["filename"] . IMAGE_SUFFIX_LARGE . "." . $p["extension"]);
		$message .= (@unlink(DIR_FS_CATALOG_IMAGES . $p['dirname'] . '/' . $p["filename"] . "." . $p["extension"]) ? '' : '<br />' . IM_CANNOT_DELETE . ' ' . DIR_FS_CATALOG_IMAGES . $p['dirname'] . '/' . $p["filename"] . "." . $p["extension"]);
		return $message;
	}		
}

// This functions checks if an existing file is physically writeable
// The standard PHP function only checks for the R/O attribute and doesn't
// detect authorisation by ACL.
function IMFileIsWriteable($file) {

	$err_write = false;
	$handle = @fopen($file,"r+");
	if ($handle) {
		$i = fclose($handle);
		$err_write = true;
	}
	return($err_write);
}
 
function IMDirIsWritable($dir) {
	static $dirs;
	
	if (!isset($dirs)) $dirs = array();
	if (isset($dirs[$dir])) return $dirs[$dir];

	$err_write = false;
	$handle = @fopen($dir."foo.txt","w+");
	if	($handle !== false) {
		fwrite ($handle, "pipo");
		$i = fclose($handle);
		if (file_exists($dir."foo.txt")) {
			@unlink($dir."foo.txt");
			if (!file_exists($dir."foo.txt")) $err_write = true;
		}
	}
	$dirs[$dir] = $err_write;
	return $err_write;
}

function IMCreateDir($dir, $parent, $recurse=false) {

	// Cleanup the dir
	if (!empty($dir)) $dir = trim($dir,"/.")."/";
	$parent = urldecode($parent);
	if (is_dir($parent.$dir)) return true;
	// Create the tree, if this is not the subordinate of an existing dir
	// We assume that the parent already exists!
	if (!$recurse) {
		$dirlevels = $dir_levels = preg_split("/\//", $dir);
		$basedir = $parent;
		foreach($dirlevels as $pipo =>$directory) {
			if (!empty($directory)) {
				$directory .= "/";
				if (!IMCreateDir($directory, $basedir, true)) {
					return false;
				}
				$basedir .= $directory;
			}
		}
	}
	if (!is_dir($parent.$dir)) {
		if (!@mkdir($parent.$dir, 0777)) {
			return false;
		}
		else {
			return true;
		}
	}
	else return true;
}

function IMGetDirList($dirs, $recursive=true) {
	static $exclude_dirs, $include_files;
	
	if (!isset($exclude_dirs)) {
		
		$exclude_dirs = array(DIR_FS_CATALOG_IMAGES . "attributes/", DIR_FS_CATALOG_IMAGES . "banners/", DIR_FS_CATALOG_IMAGES . "categories/", DIR_FS_CATALOG_IMAGES . "gift_certificates/", DIR_FS_CATALOG_IMAGES . "icons/", DIR_FS_CATALOG_IMAGES . "samples/", DIR_FS_CATALOG_IMAGES . IM_UPLOAD_TEMP_DIR, DIR_FS_CATALOG_IMAGES . "manufacturers/", DIR_FS_CATALOG_IMAGES . "testimonials/");
		$add_dirs = explode(",", IM_EXCLUDE_FOLDERS_EXTRA);
		if (count($add_dirs) > 0) {
			foreach($add_dirs as $key => $dir) {
				$add_dirs[$key] = DIR_FS_CATALOG_IMAGES . $dir;
			}
			$exclude_dirs = array_merge($exclude_dirs, $add_dirs);
		}
		$include_files = array("a11","acb","adc","adf","afm","ai","aiff","aif","amg","anm","ans","apd","asf","au","avi","awm","bga","bmp","bob","bpt","bw","cal","cel","cdr","cgm","cmp","cmv","cmx","cpi","cur","cut","cvs","cwk","dcs","dib","dmf","dng","doc","dsm","dxf","dwg","emf","enc","eps","fac","fax","fit","fla","flc","fli","fpx","ftk","ged","gif","gmf","hdf","iax","ica","icb","ico","idw","iff","img","jbg","jbig","jfif","jpe","jpeg","jp2","jpg","jtf","jtp","lwf","mac","mid","midi","miff","mki","mmm",".mod","mov","mp2","mp3","mpg","mpt","msk","msp","mus","mvi","nap","ogg","pal","pbm","pcc","pcd","pcf","pct","pcx","pdd","pdf","pfr","pgm","pic","pict","pk","pm3","pm4","pm5","png","ppm","ppt","ps","psd","psp","pxr","qt","qxd","ras","rgb","rgba","rif","rip","rla","rle","rpf","rtf","scr","sdc","sdd","sdw","sgi","sid","sng","swf","tga","tiff","tif","txt","text","tub","ul","vda","vis","vob","vpg","vst","wav","wdb","win","wk1","wks","wmf","wmv","wpd","wxf","wp4","wp5","wp6","wpg","wpp","xbm","xls","xpm","xwd","yuv","zgm");
	}

	$dirlist = array();
	if (!is_array($dirs)) $dirs = array($dirs);

	foreach ($dirs as $key=>$dir) {
		$d = @dir($dir);
		if (is_object($d)) {
			while (false !== ($entry = $d->read())) {
				if ($entry != ".." && $entry != ".") {
					$direntry = $dir.$entry."/";
					if(is_dir($direntry)) {
						if (!in_array($direntry, $exclude_dirs)) {
							if ($recursive) $dirlist = array_merge($dirlist, IMGetDirList(array($direntry)));
						}
					}
					else {
						if (IM_FILETYPES == "media") {
							$ext = pathinfo($entry, PATHINFO_EXTENSION);
							if (in_array(strtolower($ext), $include_files)) $dirlist[] = $dir.$entry;
						}
						else $dirlist[] = $dir.$entry;
					}
				}
			}
			$d->close();
		}
	}
	return $dirlist;
}
/*  Parameters:
 **	$source       : full path and name of the original file
 ** $dst		  : full path and name of the destinaton file
 ** $dst_root	  : full path to the root of the destination 
 ** $dst_type	  : large, medium or small
 ** $add_watermark: true or false
*/
function IMAddWaterMark($source, $dst, $dst_root, $dst_type, $addwatermark=true) {
	global $IMcanBAK;
	 
	// The watermark must be present in the destination root folder (images, images/medium and images/large)
	// If absent, the program assumes that on that level no watermarking will take place.
	
	// Check for extension and existence of functions
	$p = pathinfo($source);	
	if (strtolower($p["extension"]) == "jpg" && function_exists("imagecreatefromjpeg") && function_exists("imagejpeg")) {
		$temp = @imagecreatefromjpeg($source);
	}
	else if (strtolower($p["extension"]) == "gif" && function_exists("imagecreatefromgif") && function_exists("imagegif")) {
		$temp = @imagecreatefromgif($source);
	}
	else if (strtolower($p["extension"]) == "png" && function_exists("imagecreatefrompng") && function_exists("imagepng")) {
		$temp = @imagecreatefrompng($source);
	}
	else return "<br />" . IM_NO_IMAGE_FUNCTION;
	
	if ($temp == false) return "<br />" . IM_SOURCE_IMAGE_ERROR . $dst . IM_FROM . $source;
 
	// Get the resize dimensions
	$imgsize = @getimagesize($source);
	$org_w = $imgsize[0];
	$org_h = $imgsize[1];
	
	if ($dst_type == "small") {
		$cw = $org_w / SMALL_IMAGE_WIDTH;
		$ch = $org_h / SMALL_IMAGE_HEIGHT;
		if ($cw > $ch) {
			$dst_w = SMALL_IMAGE_WIDTH;
			$dst_h = round($org_h / $cw);
		}
		else {
			$dst_h = SMALL_IMAGE_HEIGHT;
			$dst_w = round($org_w / $ch);
		}
	}
	else if ($dst_type == "medium") {
		$cw = $org_w / MEDIUM_IMAGE_WIDTH;
		$ch = $org_h / MEDIUM_IMAGE_HEIGHT;
		if ($cw > $ch) {
			$dst_w = MEDIUM_IMAGE_WIDTH;
			$dst_h = round($org_h / $cw);
		}
		else {
			$dst_h = MEDIUM_IMAGE_HEIGHT;
			$dst_w = round($org_w / $ch);
		}
	}
	else if ($dst_type == "large") {
		$cw = $org_w / IM_MAX_LARGE_WIDTH;
		$ch = $org_h / IM_MAX_LARGE_HEIGHT;
		if ($cw > $ch) {
			$dst_w = IM_MAX_LARGE_WIDTH;
			$dst_h = round($org_h / $cw);
		}
		else {
			$dst_h = IM_MAX_LARGE_HEIGHT;
			$dst_w = round($org_w / $ch);
		}
	}

	// Resize the image to a new copy
	$new = imagecreatetruecolor($dst_w, $dst_h);
	imagecopyresampled($new, $temp, 0, 0, 0, 0, $dst_w, $dst_h, $org_w, $org_h);
	
	   
	if (file_exists($dst_root . "watermark.png") && $addwatermark) {
		$source_stamp = $dst_root."watermark.png";
		$stamp = imagecreatefrompng ($source_stamp);

				
		// Calculate width and horizontal position of the new watermark
		
		// Width of the existing watermark
		$sx = imagesx($stamp);
		
		// Width of the watermark to be applied to the image

		$sw = round(IM_WM_HSIZE * $dst_w / 100);

		// Get the margin from the left
		if (IM_WM_HPOS == 'middle') {
			$hmargin = round(($dst_w - $sw) / 2);
		}
		else if (IM_WM_HPOS == 'right') {
			$hmargin = $dst_w - round(IM_WM_HMARGIN * $dst_w / 100) - $sw;
		}
		else $hmargin = round(IM_WM_HMARGIN * $dst_w / 100);
		
		// Height of the watermark
		$sy = imagesy($stamp); 
		
		// Heigth of the watermark to be applied to the image
		$sh = round($sy * $sw / $sx);
		
		// Get the margin from the top
		if (IM_WM_VPOS == 'middle') {
			$vmargin = round(($dst_h - $sh) / 2);
		}
		else if (IM_WM_VPOS == 'bottom') {
			$vmargin = $dst_h - round(IM_WM_VMARGIN * $dst_h / 100) - $sh;
		}
		else $vmargin = round(IM_WM_VMARGIN * $dst_h / 100);

		imagealphablending ($stamp, true);
		
		// Copy the watermark over the picture
		imagecopyresampled ($new, $stamp, $hmargin, $vmargin, 0, 0, $sw, $sh, $sx, $sy);
		imagedestroy($stamp);
	}
	if (file_exists($dst)) {
		// If no bin specified, copy the bak file to the same folder
		if (!(boolean)trim(IM_BAK_DIR)) {
			@unlink($dst.".txt");
			copy($dst, $dst.".txt");
		}
		// Only copy if the destination folder is there and writable
		elseif ($IMcanBAK) {
			$p = pathinfo($dst);
			$destination = DIR_FS_CATALOG_IMAGES . IM_BAK_DIR . $p["filename"] . "." . $p["extension"] . ".txt";
			@unlink($destination);
			copy ($dst, $destination);
		}
	}
	if (strtolower($p["extension"]) == "jpg") imagejpeg ($new, $dst, IM_IMAGE_QUALITY);
	if (strtolower($p["extension"]) == "gif") imagegif ($new, $dst);
	if (strtolower($p["extension"]) == "png") imagepng ($new, $dst, round(abs((IM_IMAGE_QUALITY - 100) / 11.111111)));
		
	imagedestroy ($temp);
	imagedestroy ($new);
	return "";
}

function IMfilesort($a, $b) {
	
	if ($a["dir"] == $b["dir"]) return strnatcasecmp($a["file"], $b["file"]); 
	else return strnatcasecmp($a["dir"], $b["dir"]);
}

function IMIDSort($a, $b) {
	return ($a[0][0] > $b[0][0] ? 1 : ($a[0][0] < $b[0][0] ? -1 : 0));
}

function IMSizeLSort($a, $b) {
	global $images;
	
	// Both are not an image or don't exist
	if ((!$images[$a]["large"]["exists"] || !$images[$a]["large"]["is_image"]) && (!$images[$b]["large"]["exists"] || !$images[$b]["large"]["is_image"])) return strnatcasecmp($images[$a]["filename"], $images[$b]["filename"]);
	
	// $a is not an image or doesn't exist
	if (!$images[$a]["large"]["exists"] || !$images[$a]["large"]["is_image"]) return -1;
	
	// $b is not an image or doesn't exist
	if (!$images[$b]["large"]["exists"] || !$images[$b]["large"]["is_image"]) return 1;
	return ($images[$a]["large"]["size"] > $images[$b]["large"]["size"]) ? 1 : -1;
}

function IMPrintPageSelector($count, $current, $width) {
	global $IMstatus, $IMatt, $IMerror, $IMimage, $IMorder, $IMfilter, $IMpage;
	static $counter;
	
	if (!isset($counter)) $counter = 0;
	else $counter++;
	
	// Only do something if there is more than 1 page
	if ($count > IM_PAGE_LENGTH) {
		
		// Calculate the number of pages 
		$pages = floor(($count - 1) / IM_PAGE_LENGTH) + 1;
		
		// If the current page is larger than the max page (after deletes) reset the page number
		if ($IMpage > $pages) $IMpage = $pages;
		if ($current > $pages) $current = $pages;
		
		// Calculate the start item #
		$from = ($current - 1) * IM_PAGE_LENGTH + 1;
		// and the end item #
		$to = $current * IM_PAGE_LENGTH;
		if ($to > $count) $to = $count;
	
		// Print the container
		print "<div align=center style='width:" . $width . "%;'>";
		
		// Print the info text
		print "<div class='smallText' align=left style='float:left; width:20%;'>";
		print IM_SHOW . '&nbsp;&nbsp;<b>' . $from . '</b>&nbsp;&nbsp;' . IM_TO . '&nbsp;&nbsp;<b>' . $to . '</b>&nbsp;&nbsp;' . IM_OF . '&nbsp;&nbsp;<b>' . $count . '</b>';
		print "</div>";
		
		// Print the page links
		print "<div class='smallText' align=right style='float:right; width:20%;'>";
		
		// Previous page
		if ($current > 1) print "<a href=\"javascript:\" onclick=\"if (CheckForm(image_manager)) {document.image_manager.IMpage.value='" . ($current - 1) . "'; document.image_manager.submit(); } return false;\">" . "&lt;&lt;&nbsp;&nbsp;" . "</a>";
		
		// Dropdown
		$values = array();
		for ($page = 1; $page <= $pages; $page++) {
			$values[] = array('id' => $page, 'text' => $page);
		}
		print IM_PAGE . '&nbsp;&nbsp;' . zen_draw_pull_down_menu('IMpage' . $counter, $values, $current, 'onchange="if (CheckForm(image_manager)) {document.image_manager.IMpage.value=this.value; document.image_manager.submit();}"') . '&nbsp;&nbsp;' . IM_OF. '&nbsp;&nbsp;' . $pages;
		// Next page
		if ($pages > $current) print "<a href=\"javascript:\" onclick=\"if (CheckForm(image_manager)) { document.image_manager.IMpage.value='" . ($current + 1) . "'; document.image_manager.submit();} return false;\">" . "&nbsp;&nbsp;&gt;&gt;" . "</a>";
		print "</div>";
		
		// Close the container
		print "</div><br class='clearBoth' />";
		
		// return the index value to start the output with
		return ($from - 1);
	}
}
function IMCheckUploadFolder($msg=true) {
	
	// Check if the upload folder exists
	if (!is_dir(DIR_FS_CATALOG_IMAGES . IM_UPLOAD_TEMP_DIR)) {
		// If not, create it
		if (IMCreateDir(trim(IM_UPLOAD_TEMP_DIR, '/'), DIR_FS_CATALOG_IMAGES)) {
			if ($msg) IMPrintError(IM_DIR_CREATED . DIR_FS_CATALOG_IMAGES . IM_UPLOAD_TEMP_DIR);
		}
		else {
			if ($msg) IMPrintError(IM_DIR_EXISTS_ERROR . DIR_FS_CATALOG_IMAGES . IM_UPLOAD_TEMP_DIR);
			return false;
		}
	}
	// If it exists, check if we can write in it
	else if (!IMDirIsWritable(DIR_FS_CATALOG_IMAGES . IM_UPLOAD_TEMP_DIR)) {
		if ($msg) IMPrintError(IM_DIR_WRITE_ERROR . DIR_FS_CATALOG_IMAGES . IM_UPLOAD_TEMP_DIR);
		return false;
	}
	return true;
}

function IMCheckBAKFolder($msg=true) {
	
	// If no backup folder specified, no need to check
	if (!(boolean)trim(IM_BAK_DIR)) return true;
	
	// Check if the backup folder exists
	if (!is_dir(DIR_FS_CATALOG_IMAGES . IM_BAK_DIR)) {
		// If not, create it
		if (IMCreateDir(trim(IM_BAK_DIR, '/'), DIR_FS_CATALOG_IMAGES)) {
			if ($msg) IMPrintError(IM_DIR_CREATED . DIR_FS_CATALOG_IMAGES . IM_BAK_DIR);
		}
		else {
			if ($msg) IMPrintError(IM_DIR_EXISTS_ERROR . DIR_FS_CATALOG_IMAGES . IM_BAK_DIR . ". " . IM_CANNOT_SAVE_BAK);
			return false;
		}
	}
	// If it exists, check if we can write in it
	else if (!IMDirIsWritable(DIR_FS_CATALOG_IMAGES . IM_BAK_DIR)) {
		if ($msg) IMPrintError(IM_DIR_WRITE_ERROR . DIR_FS_CATALOG_IMAGES . IM_BAK_DIR . ". " . IM_CANNOT_SAVE_BAK);
		return false;
	}
	return true;
}

function IMPrintError($msg, $break=true, $return=false) {
	
	if ($return) return '<span class="errorText">' . $msg . '</span>' . ($break ? '<br />' : '');
	else print '<span class="errorText">' . $msg . '</span>' . ($break ? '<br />' : '');
}
?>